<template>
  <div class="chat-window">
    <!-- 消息显示区域 -->
    <div class="chat-messages">
      <div v-for="(message, index) in messages" :key="index" class="message" id="messageContainer">
        

        <div class="card" :class="message.sender === '用户' ? 'user-message' : 'other-message'">
          
          <div>
            <el-tag type="success">{{ message.sender }} </el-tag>
            </div>
          <div>{{ message.content }}</div>
        </div>
      </div>
    </div>
    <!-- 消息输入区域 -->
    <div class="chat-input">
      <el-input
        type="textarea"
        v-model="newMessage"
        placeholder="请输入消息"
        style="width: 80%"
       
      ></el-input>

     
     
      <el-button type="primary" @click="sendMessage">发送</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      prompt: "",
      messages: [{ sender: "系统", content: "欢迎进入聊天窗口！" },
        { sender: "系统", content: "请输入你的问题" },
        { sender: "用户", content: "你好" },
      ],
      newMessage: "",
    };
  },
  methods: {

   
    sendMessage() {
      // const message = document.getElementById("message-input").value;
      let that = this; 
      if (this.newMessage) {
        this.messages.push({ sender: '用户', content: this.newMessage});
        const eventSource = new EventSource(
          "/api/api/ai/chat?prompt=" + this.newMessage,
          {
            headers: {
              "Content-Type": "application/json",
            },
            method: "GET",
            body: JSON.stringify({ prompt: this.newMessage }),
          }
        );

        // const chatOutput = document.getElementById("chat-output");
        eventSource.onmessage = function (event) {
          // chatOutput.innerHTML += event.data;
          console.log(event.data);
          
          that.messages.push({ sender: '对方', content: event.data});

            // 获取消息容器元素
            const container = document.getElementById('messageContainer');

          // 将新消息添加到消息容器中
          // container.appendChild(newMessage);
            // 滚动到容器的底部
            container.scrollTop = container.scrollHeight;
        };

        eventSource.onerror = function (error) {
          console.log(error);
          // alert(error)
          // chatOutput.innerHTML += `Error: ${error.message}`;
          eventSource.close();
        };
      }
    },
  },
};
</script>

<style lang="scss" scoped>

.chat-window {
  height: calc(100vh - 100px);
  width: 80%;
  margin: 5px auto;
  border: 1px solid #ccc;
  border-radius: 5px;
  overflow: hidden;
}

.chat-messages {
  height: calc(100vh - 180px);
  overflow-y: auto;
  padding: 10px;
  .card {

    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 10px;

    .user-message{
      text-align: right;
    }

  }
}

.message {
  margin-bottom: 10px;
}

.chat-input {
  display: flex;
  align-items: center;
  padding: 10px;
  border-top: 1px solid #ccc;
}
</style>
